﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceLibrary.Model;
using ServiceLibrary.DLayer;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Globalization;
using System.IO;
using System.ServiceModel;
using System.Threading;
using System.Web;

namespace ServiceLibrary.BLayer
{
    public class Function
    {
        private static bool Validate_NotificaEvento;
        private static ErrorManager _errorManager = new DLayer.ErrorManager();

        #region SISM_Soap_Log

        public static void SISM_Soap_Log(string guid, string envelopeIN, string endPoint)
        {
            Z_SISM_Soap_Log dbLog = new Z_SISM_Soap_Log();

            dbLog.Execute(guid, envelopeIN, endPoint);
        }

        #endregion

        #region Serialize / Deserialize

        public static String SerializeToXmlString(object targetInstance)
        {
            string retVal = string.Empty;

            TextWriter writer = new StringWriter();
            XmlSerializer serializer = new XmlSerializer(targetInstance.GetType());
            serializer.Serialize(writer, targetInstance);
            retVal = writer.ToString();

            return retVal;
        }

        public static object DeserializeFromXmlString(string objectXml, Type targetType)
        {
            object retVal = null;

            XmlSerializer serializer = new XmlSerializer(targetType);
            StringReader stringReader = new StringReader(objectXml);
            XmlTextReader xmlReader = new XmlTextReader(stringReader);
            retVal = serializer.Deserialize(xmlReader);

            return retVal;
        }

        #endregion

        #region Validate
        /// <summary>
        /// Validate SCHEMA "ServiceLibrary\SCHEMA\SGTSchema.xsd"
        /// </summary>
        /// <param name="targetInstance">object Instance</param>
        /// <param name="schemaPath">Es: ServiceLibrary\SCHEMA\SGTSchema.xsd</param>
        /// <returns></returns>
        public static bool Validate(string guid, object targetInstance, string schemaPath)
        {
            Validate_NotificaEvento = true;
            _errorManager.GUID = guid;

            try
            {
                string virtualDir = "" + HttpRuntime.AppDomainAppPath;

                //if (virtualDir == "")
                //{
                //    string[] _listOfDir = HttpRuntime.AppDomainAppPath.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);

                //    for (int index = 0; index < _listOfDir.Length - 1; index++)
                //    {
                //        virtualDir += _listOfDir[index] + "\\";
                //    }
                //}

                /****************************************/
                string xsd = virtualDir + schemaPath;
                /****************************************/

                XmlReaderSettings settings = new XmlReaderSettings();
                /****************************************/
                settings.Schemas.Add("http://www.csi.it/sisminvi/", xsd);
                /****************************************/
                settings.ValidationType = ValidationType.Schema;

                String xml = SerializeToXmlString(targetInstance);

                settings.ValidationEventHandler += new ValidationEventHandler(Settings_ValidationEventHandler);

                XmlReader reader = XmlReader.Create(new StringReader(xml), settings);
                XmlDocument document = new XmlDocument();

                document.Load(reader);
            }
            catch (Exception ex)
            {
                Validate_NotificaEvento = false;
                throw new Exception("# Validate: " + ((ex.InnerException != null) ? ex.InnerException.ToString() : ex.Message.ToString()));
            }

            return Validate_NotificaEvento;
        }

        /// <summary>
        /// Handler to Validate SCHEMA "Schema\NotificaEventoAURA.xsd"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void Settings_ValidationEventHandler(object sender, ValidationEventArgs e)
        {
            Validate_NotificaEvento = false;

            string strErrorMsg = "";

            if (e.Severity == XmlSeverityType.Warning)
                strErrorMsg += "WARNING: ";
            else
                strErrorMsg += "ERROR: ";

            strErrorMsg += e.Exception.Message + @"\r\n";

            _errorManager.SISM_ErrorDetail_put(strErrorMsg, "XSD VALIDATION");
        }

        #endregion

        #region ErrorManager

        public static string ErrorManager(string codice, string messaggio, string rootName)
        {
            return Z_SISM_ErrorManager.Execute(codice, messaggio, rootName);
        }

        #endregion

    }
}
